#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <dirent.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/socket.h>

#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"
#include "user_define.h"
#include "node_define.h"
#include "data_define.h"
#include "node_collect.h"

extern struct timeval time_val;

int origin_time=0;

int node_collect_init(void * sub_proc,void * para)
{
	int ret;
	// add youself's plugin init func here
    origin_time=time(&origin_time);
    print_cubeaudit("origin time is %d",origin_time);
	
	return 0;
}

int node_collect_start(void * sub_proc,void * para)
{
	int ret;
	int i;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here


    printf("tv_usec value is %d\n",node_collect_val.tv_usec);

	while(1)
	{
		usleep(node_collect_val.tv_usec);
		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg!=NULL)
        {
		    type=message_get_type(recv_msg);
		    subtype=message_get_subtype(recv_msg);
        
            if(type != TYPE(NODE_DEFINE))
            {
                continue;
            }
            proc_node_collect_set(sub_proc,recv_msg);

        }
	}
	
	return 0;
}

int proc_node_collect_set(void * sub_proc,void * recv_msg)
{
	int ret;
	int i;
    RECORD(NODE_DEFINE,BASIC_INFO) * input;
    RECORD(NODE_DEFINE,CONFIG) * config;
    DB_RECORD * db_record;

    ret=message_get_record(recv_msg,&input,0);
    if(input==NULL)
    {
        return -EINVAL;
    }
    db_record = memdb_store(input,TYPE_PAIR(NODE_DEFINE,BASIC_INFO),NULL);
    if(db_record == NULL)
        return -EINVAL;
    config = Talloc0(sizeof(*config));
    if(config==NULL)
        return -ENOMEM;
    config->node_name=dup_str(input->node_name,DIGEST_SIZE);
    config->origin=origin_time;

    
	void * new_msg;
	new_msg=message_create(TYPE_PAIR(NODE_DEFINE,CONFIG),recv_msg);
    if(new_msg==NULL)
        return -EINVAL;
    ret=message_add_record(new_msg,config);
	if(ret<0)
		return ret;
	ret=ex_module_sendmsg(sub_proc,new_msg);
	return ret;
}
